// 判断设备类型
function checkDeviceType() {
  const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth <= 768;
  document.body.classList.add(isMobile ? 'mobile-device' : 'pc-device');
  return isMobile;
}

window.onload = function () {
  // 判断设备类型
  const isMobile = checkDeviceType();
  
  // 左侧切换
  $('.auContent .auContentTab .ctBottom .ctItem').on('click', function () {
    $(this).addClass('active').siblings().removeClass('active');
    const dataId = this.getAttribute('data-id');
    document.querySelectorAll('.auContent .auContentTab').forEach(div => {
      div.classList.remove('active');
    });
    document.getElementById(dataId).classList.add('active');
  });

  $('.auContent .sidebar-toggle').on('click', function () {
    var tab = document.querySelector('.auContent .auContentTab');
    if(tab) {
      tab.style.transform = 'translateX(0%)';
      tab.classList.toggle('active');
    }
  });

  $(function(){
    var domlist = $('.auContent .auContentDetail .cdContent.cdContent2 .cdContentSComposition .SCompositionItem .SCItemRight');
    $.each(domlist, function (index, val) {
        var height = $(val).find('.SCItemRBottom').height();
        console.log('height', height);
        if (height > 140) {
          $(val).find('.SCItemRBottom').addClass('active');
          $(val).find('.RtopBtn').remove();
          var str = "<div class='RtopBtn'>展开</div>";
          $(val).append(str).show();
        } else {
          $(val).find('.SCItemRBottom').removeClass('active');
          $(val).find('.RtopBtn').remove();
          // $(val).find('.RtopBtn').hide()
        }
    });
    // 展开
    $('.cdContent.cdContent2 .cdContentSComposition .SCompositionItem .SCItemRight .RtopBtn').on('click', function () {
      $(this).prev().toggleClass('active');
      $(this).toggleClass('active');
      if ($(this).hasClass('active')) {
        $(this).text('收起');
      } else {
        $(this).text('展开');
      }
    });
  }) 

  // 侧边栏一级菜单点击
  document.querySelectorAll('.ctBottom .ctItem').forEach(function (item) {
    item.addEventListener('click', function (e) {
      if (e.target.classList.contains('ctItemNameChildItem')) return;
      // 一级高亮
      document.querySelectorAll('.ctBottom .ctItem').forEach(i => i.classList.remove('active'));
      this.classList.add('active');
      // 二级全部隐藏，当前显示
      document.querySelectorAll('.ctBottom .ctItem .ctItemChild').forEach(child => child.style.display = 'none');
      var childMenu = this.querySelector('.ctItemChild');
      if(childMenu) {
        childMenu.style.display = 'block';
        // 判断是否有二级菜单项
        var subItems = childMenu.querySelectorAll('.ctItemNameChildItem');
        if(subItems.length > 0) {
          // 有二级菜单，仅展开二级菜单，不切换内容，不关闭侧边栏
          // 不再自动高亮第一个二级菜单
          // 将侧边栏菜单的transform样式设置为translateX(0%)
          var tab = document.querySelector('.auContent .auContentTab');
          if(tab) {
            tab.style.transform = 'translateX(0%)';
          }
          document.querySelector('.hero-content').style.display='none';
          document.querySelectorAll('.ywly-content').forEach(c => c.classList.remove('active'));
          // 默认显示第一个内容区
          var firstContent = document.querySelector('.ywly-content');
          if(firstContent) firstContent.classList.add('active');
          return;
        }
      }
      debugger
      // 没有二级菜单，直接切换内容并关闭侧边栏
      var dataId = this.getAttribute('data-id');
      document.querySelectorAll('.ywly-content').forEach(c => c.classList.remove('active'));
      var content = document.getElementById(dataId);
      if(content) content.classList.add('active');
      
      // closeSidebar();
    });
  });
  // 默认只显示第一个一级的二级菜单
  document.querySelectorAll('.ctBottom .ctItem').forEach(function(item, idx){
    var childMenu = item.querySelector('.ctItemChild');
    if(childMenu) childMenu.style.display = idx === 0 ? 'block' : 'none';
  });
  // 二级菜单点击
  document.querySelectorAll('.ctBottom .ctItem .ctItemNameChildItem').forEach(function (subItem) {
    subItem.addEventListener('click', function (e) {
      // 只高亮当前二级
      var siblings = this.parentNode.parentNode.querySelectorAll('.ctItemNameChildItem');
      siblings.forEach(i => i.classList.remove('active'));
      this.classList.add('active');
      // 一级菜单保持高亮（不变）
      e.stopPropagation();
      // 切换右侧内容区
      var dataId = this.getAttribute('data-id') || this.getAttribute('data-type');
      document.querySelectorAll('.ywly-content').forEach(c => c.classList.remove('active'));
      var content = document.getElementById(dataId);
      if(content) content.classList.add('active');
    });
  });
  // 默认显示第一个内容区
  var firstContent = document.querySelector('.ywly-content');
  if(firstContent) firstContent.classList.add('active');
};

// 默认显示第一个
window.addEventListener('DOMContentLoaded', function() {
  const firstContent = document.querySelector('.ywly-main .ywly-content');
  if(firstContent) firstContent.classList.add('active');
  if(firstContent && firstContent.id === 'tab1') {
    setupProjectListPagination();
  }
});

// 项目列表数据与分页渲染
const projectListData = [
  { title: '城市活动断层探测与地震危险性分析', date: '2023-05-08' },
  { title: '活动断层填图与活动性鉴定', date: '2023-04-24' },
  { title: '重大工程地质问题专项', date: '2023-04-24' },
  { title: '设计地震动时程分析', date: '2023-04-24' },
  { title: '重大工程地震安全性评价', date: '2023-04-19' },
  { title: '地震小区划及区域地震安全性评价', date: '2023-10-08' },
  { title: '城市震害预测', date: '2023-10-08' },
  { title: '地震灾害情景构建', date: '2023-09-22' },
  { title: '城市活动断层探测与地震危险性分析21', date: '2023-05-08' },
  { title: '活动断层填图与活动性鉴定21', date: '2023-04-24' },
  { title: '重大工程地质问题专项21', date: '2023-04-24' },
  { title: '设计地震动时程分析21', date: '2023-04-24' },
  { title: '重大工程地震安全性评价21', date: '2023-04-19' },
  { title: '地震小区划及区域地震安全性评价21', date: '2023-10-08' },
  { title: '城市震害预测21', date: '2023-10-08' },
  { title: '地震灾害情景构建21', date: '2023-09-22' },
  { title: '城市活动断层探测与地震危险性分析22', date: '2023-05-08' },
  { title: '活动断层填图与活动性鉴定22', date: '2023-04-24' },
  { title: '重大工程地质问题专项22', date: '2023-04-24' },
  { title: '设计地震动时程分析22', date: '2023-04-24' },
  { title: '重大工程地震安全性评价22', date: '2023-04-19' },
  { title: '地震小区划及区域地震安全性评价22', date: '2023-10-08' },
  { title: '城市震害预测22', date: '2023-10-08' },
  { title: '地震灾害情景构建22', date: '2023-09-22' },
  // 可继续添加更多数据
];
const PAGE_SIZE = 8;
function renderProjectList(page = 1) {
  const start = (page - 1) * PAGE_SIZE;
  const end = start + PAGE_SIZE;
  const list = projectListData.slice(start, end);
  const container = document.getElementById('project-list-container');
  if (!container) return;
  container.innerHTML = list.map(item => `
    <div class="project-list-item">
      <div class="project-list-title"><span class="project-list-dot"></span>${item.title}</div>
      <div class="project-list-date">${item.date}</div>
    </div>
  `).join('');
}
function renderPagination(current = 1) {
  const total = projectListData.length;
  const pageCount = Math.ceil(total / PAGE_SIZE);
  const container = document.getElementById('pagination-container');
  if (!container || pageCount <= 1) {
    if(container) container.innerHTML = '';
    return;
  }
  let html = '<div class="pagination">';
  html += `<button class="pagination-btn" ${current === 1 ? 'disabled' : ''} data-page="${current-1}">上一页</button>`;
  for(let i=1; i<=pageCount; i++) {
    html += `<button class="pagination-btn${i===current?' active':''}" data-page="${i}">${i}</button>`;
  }
  html += `<button class="pagination-btn" ${current === pageCount ? 'disabled' : ''} data-page="${current+1}">下一页</button>`;
  html += '</div>';
  container.innerHTML = html;
  // 事件绑定
  container.querySelectorAll('.pagination-btn').forEach(btn => {
    btn.addEventListener('click', function() {
      const page = parseInt(this.getAttribute('data-page'));
      if(!isNaN(page) && page >= 1 && page <= pageCount) {
        renderProjectList(page);
        renderPagination(page);
      }
    });
  });
}
// tab2激活时渲染
function setupProjectListPagination() {
  renderProjectList(1);
  renderPagination(1);
}
// 顶部下拉菜单点击联动左侧tab
document.querySelectorAll('.dropdown-menu a[data-tab]').forEach(link => {
  link.addEventListener('click', function(e) {
    // e.preventDefault();
    const newUrl = e.target.href;
    history.pushState({}, '', newUrl); // 更新地址栏
    const tab = this.getAttribute('data-tab');
    // 激活左侧菜单
    const sideLink = document.querySelector('.ywly-sidebar a[data-tab="' + tab + '"]');
    if (sideLink) sideLink.click();
  });
});

function getQueryParam(name) {
  const url = window.location.search;
  const params = new URLSearchParams(url);
  return params.get(name);
}

window.addEventListener('DOMContentLoaded', function() {
  const tabParam = getQueryParam('tab');
  let targetTab = tabParam || 'tab1';
  // 激活侧边栏
  document.querySelectorAll('.ywly-sidebar a').forEach(a => {
    if(a.getAttribute('data-tab') === targetTab) {
      a.classList.add('active');
    } else {
      a.classList.remove('active');
    }
  });
  // 激活内容区
  document.querySelectorAll('.ywly-main .ywly-content').forEach(div => {
    if(div.id === targetTab) {
      div.classList.add('active');
    } else {
      div.classList.remove('active');
    }
  });
  if(targetTab === 'tab2') {
    setupProjectListPagination();
  }
});

// 手机端：点击菜单项后自动关闭侧边栏，点击遮罩关闭侧边栏
function closeSidebar() {
  var sidebar = document.querySelector('.auContentTab');
  if(sidebar) {
    sidebar.classList.remove('active');
    sidebar.style.transform = 'translateX(-100%)';
  }
  var mask = document.querySelector('.sidebar-mask');
  if(mask) {
    mask.style.opacity = '0';
    setTimeout(function(){ mask.style.display = 'none'; }, 300);
  }
  var heroContent = document.querySelector('.hero-ywly .hero-content');
  if(heroContent) heroContent.style.display = 'block';
}
function toggleSidebar() {
  var sidebar = document.querySelector('.auContentTab');
  var mask = document.querySelector('.sidebar-mask');
  var heroContent = document.querySelector('.hero-ywly .hero-content');
  if(sidebar) sidebar.classList.toggle('active');
  if(mask) {
    if(sidebar.classList.contains('active')) {
      mask.style.display = 'block';
      setTimeout(function(){ mask.style.opacity = '1'; }, 10);
    } else {
      mask.style.opacity = '0';
      setTimeout(function(){ mask.style.display = 'none'; }, 300);
    }
  }
  if(heroContent) heroContent.style.display = sidebar.classList.contains('active') ? 'none' : 'block';
}
function bindSidebarAutoClose() {
  if(window.innerWidth <= 600) {
    document.querySelectorAll('.ctBottom .ctItem, .ctBottom .ctItemNameChildItem').forEach(function(item){
      item.onclick = function() { closeSidebar(); };
    });
    var btn = document.getElementById('sidebarToggleBtn');
    if(btn) btn.onclick = toggleSidebar;
    var mask = document.querySelector('.sidebar-mask');
    if(mask) mask.onclick = closeSidebar;
  }
}
bindSidebarAutoClose();
window.addEventListener('resize', bindSidebarAutoClose);